/**
 * Created by Jie on 2017/2/7.
 */
var async = require('async');
var Model = require('../../model/core/role_fk_menu');
var Menu = require('../../model/core/menu');

var index = {page:'core/_form/_role_fk_menu',title:''};

exports.index = function (req,res) {
    var menu = new Menu();
    var model = new Model();
    var cond = {where:'',order:' sort desc'};
    var roleId = req.params.roleId;
    async.waterfall([
        function(callback) {
            model.findByRoleId(roleId,function (err,result) {
                callback(null,result);
            });
        },
        function(vals, callback) {
            menu.all(cond,function (err,result) {
                if(vals.error == 1){
                    callback(null,result);
                }else {
                    var data = result.data;
                    var roleMenu = vals.data;
                    for(var i=0;i<data.length;i++){
                        data[i].check = 0;
                        if(formatRole(data[i].id,roleMenu)){
                            data[i].check = 1;
                        }
                    }
                    result.data = data;
                }
                callback(null,result);
            })

        }
    ], function(error, result) {
        res.render(index.page, {title: index.title,result:result,roleId:roleId});
    });
};

exports.auth = function (req,res) {
    var model = new Model();
    model.auth(req.body.vals,function (err,result) {
        res.json(result)
    })
}

function formatRole(_id,_list) {
    var ok = false;
    for(var i=0;i<_list.length;i++){
        if(_id == _list[i].menuId){
            ok = true;
            break;
        }
    }
    return ok;
}